<template>
    <div class="forget-container">
        <div class="forget-title">
            找回密码
        </div>

        <div class="forget-form-box">
            <el-row :gutter="20">
                <el-col :span="10">
                    <el-form v-show="changePasswordBtnDisabled"
                             :ref="forgetPasswordForm"
                             :model="sobUser"
                             :rules="rules"
                             label-position="right" label-width="80px">
                        <el-form-item label="验证码" :required="true" prop="captcha">
                            <el-input v-model="sobUser.captcha" placeholder="输入验证码"></el-input>

                            <img :src="captchaPath" alt="获取验证码失败"
                                 @click="updateCaptchaCode"
                                 class="captcha-code-cursor">
                        </el-form-item>
                        <el-form-item label="邮箱" :required="true" prop="email">
                            <el-input v-model="sobUser.email" placeholder="输入邮箱地址"></el-input>
                        </el-form-item>
                        <el-form-item label="验证码" :required="true" prop="verifyCode">
                            <el-row :gutter="10">
                                <el-col :span="11">
                                    <el-input v-model="sobUser.verifyCode" placeholder="输入邮箱验证码"></el-input>
                                </el-col>
                                <el-col :span="11">
                                    <el-button type="primary" size="mini" @click="sendEmailVerifyCode"
                                               v-text="sendVerifyBtnText" :disabled="sendVerifyBtnText !== '发送验证码'">
                                    </el-button>
                                </el-col>
                            </el-row>
                        </el-form-item>
                    </el-form>

                    <el-form :model="sobUser" label-width="80px"
                             v-show="!changePasswordBtnDisabled">
                        <el-form-item label="新密码" prop="password" required>
                            <el-input v-model="sobUser.password" placeholder="" show-password></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button size="medium" type="primary" @click="updatePasswordByEmail">修改密码
                            </el-button>
                        </el-form-item>
                    </el-form>

                </el-col>
            </el-row>
        </div>
    </div>
</template>

<script>
import {
    checkCaptchaCode,
    checkEmailUnique,
    checkEmailVerifyCode,
    sendEmailVerifyCode,
    updatePasswordByEmail
} from "assets/api/userApi";
import {success_code} from "assets/utils/LRConstant";
import {hex_md5} from "assets/utils/md5";

export default {
    name: "index",
    data() {
        return {
            forgetPasswordForm: 'forgetPasswordForm',
            captchaPath: '',
            sendVerifyBtnText: "发送验证码",
            changePasswordBtnDisabled: true,
            sobUser: {
                password: '',
                email: '',
                captcha: '',
                verifyCode: ''
            },
            rules: {
                email: [
                    {required: true, message: '邮箱不能为空', trigger: ['change', 'blur']},
                    {validator: this.checkEmail, trigger: 'blur'}
                ],
                captcha: [
                    {required: true, message: '验证码不能为空', trigger: ['change', 'blur']},
                    {validator: this.checkCaptchaCode, trigger: 'blur'}
                ],
                verifyCode: [
                    {required: true, message: '邮箱验证码不能为空', trigger: ['change', 'blur']},
                    {validator: this.checkEmailVerifyCode, trigger: ['change', 'blur']}
                ]
            }
        }
    },
    methods: {
        checkEmailVerifyCode(rule, value, callback) {
            this.$refs[this.forgetPasswordForm].clearValidate();

            this.$refs[this.forgetPasswordForm].validateField("email", (val) => {
                if (!val) {
                    checkEmailVerifyCode(this.sobUser.email, value).then((result) => {
                        if (result.code === success_code) {
                            this.changePasswordBtnDisabled = false;
                            callback();
                        } else {
                            callback(new Error("邮箱验证码不正确"));
                        }
                    })
                } else {
                    callback(new Error("先输入正确的邮箱"));
                }
            })
        },
        checkCaptchaCode(rule, value, callback) {
            checkCaptchaCode(value).then((result) => {
                if (result.code === success_code) {
                    callback();
                } else {
                    callback(new Error("验证码不正确"));
                }
            })
        },
        checkEmail(rule, value, callback) {
            if (value === '') {
                callback(new Error('邮箱不能为空'));
            } else {
                const reg = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;

                if (!reg.test(value)) {
                    callback(new Error("邮箱格式不正确"));
                }

                checkEmailUnique(value, "").then((result) => {
                    // 4004 邮箱已经存在
                    // 4043 邮箱不存在
                    if (result.code === 4043) {
                        callback(new Error("未注册的邮箱"));
                    } else if (4004) {
                        callback();
                    }
                });
            }
        },
        validatePass(rule, value, callback) {
            if (value === '') {
                callback(new Error('请输入密码'));
            }

            var patrn = /^[0-9]{1,20}$/;
            if (patrn.test(value)) {
                callback(new Error('不能纯数字'));
            }

            if (value.length < 6) {
                callback(new Error('密码不能少于6位'));
            }
            callback();
        },
        checkUserName(rule, value, callback) {
            if (value === '') {
                callback(new Error('用户名不能为空'));
            }
            callback();
        },
        // 点击切换验证码
        updateCaptchaCode: function () {
            // 为节约资源 一直使用一个时间戳
            // 只有单人系统才能这么做
            // 但是会导致url 一直一样， vue 不会修改界面
            // 所以添加了一个随机参数 来改变url
            this.captchaPath = "/user/captcha?random=" + Date.parse(new Date());
        },
        sendEmailVerifyCode() {
            this.$refs[this.forgetPasswordForm].clearValidate();

            this.$refs[this.forgetPasswordForm].validateField("captcha", (val) => {
                if (val) {
                    this.$message.warning("确认填写内容是否正确");
                    return;
                } else {
                    this.$refs[this.forgetPasswordForm].validateField("email", (val) => {
                        if (!val) {
                            sendEmailVerifyCode(this.sobUser.email).then((result) => {
                                if (result.code === success_code) {
                                    // change ui
                                    let clickBtnInterval = 15;

                                    let interval = setInterval(() => {
                                        clickBtnInterval--;
                                        if (clickBtnInterval <= 0) {
                                            this.sendVerifyBtnText = "发送验证码";
                                            clearInterval(interval)
                                            return;
                                        }

                                        this.sendVerifyBtnText = "重新发送(" + clickBtnInterval + ")";
                                    }, 1000);

                                    this.$message.success("发送验证码成功")
                                } else {
                                    this.$message.error("发送验证码失败 cause by:" + result.message);
                                }
                            });
                        } else {
                            this.$message.warning("确认填写内容是否正确");
                        }
                    });
                }
            });


        },
        updatePasswordByEmail() {
            let user = {
                email: this.sobUser.email,
                password: hex_md5(this.sobUser.password)
            }
            updatePasswordByEmail(this.sobUser.verifyCode, user).then((result) => {
                if (result.code === success_code) {
                    this.$message.error("更新密码成功");
                    location.href = '/login';
                } else {
                    this.$message.error(result.message);
                }
            })
        }
    }
    ,
    mounted: function () {
        // init data
        this.updateCaptchaCode()
    }
}
</script>

<style scoped>
.forget-form-box {
    margin-top: 20px;
}

.forget-container {
    background-color: white;
    margin-top: 10px;
    margin-bottom: 50px;
    padding: 10px;
    box-shadow: 0 1px 10px #afafaf;
    border-radius: 4px;
}

.forget-title {
    font-weight: 500;
    font-size: 20px;
}
</style>